package com.hospital.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import com.hospital.common.utils.StringUtils;
import com.hospital.common.core.page.TableDataInfo;
import com.hospital.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hospital.workstation.constant.DictConstants;
import com.hospital.workstation.domain.FirstLevel;
import com.hospital.workstation.domain.PatientBaseInfo;
import com.hospital.workstation.domain.bo.FirstLevelBo;
import com.hospital.workstation.mapper.FirstLevelMapper;
import com.hospital.workstation.mapper.PatientBaseInfoMapper;
import com.hospital.workstation.utils.CareLevelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.hospital.workstation.domain.bo.TwoLevelBo;
import com.hospital.workstation.domain.vo.TwoLevelVo;
import com.hospital.workstation.domain.TwoLevel;
import com.hospital.workstation.mapper.TwoLevelMapper;
import com.hospital.workstation.service.ITwoLevelService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 医学二级监护信息Service业务层处理
 *
 * @author whb
 * @date 2023-04-19
 */
@RequiredArgsConstructor
@Service
public class TwoLevelServiceImpl implements ITwoLevelService {

    private final TwoLevelMapper baseMapper;
    private final PatientBaseInfoMapper patientBaseInfoMapper;
    private final FirstLevelMapper firstLevelMapper;

    /**
     * 查询医学二级监护信息
     */
    @Override
    public TwoLevelVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询医学二级监护信息列表
     */
    @Override
    public TableDataInfo<TwoLevelVo> queryPageList(TwoLevelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TwoLevel> lqw = buildQueryWrapper(bo);
        Page<TwoLevelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询医学二级监护信息列表
     */
    @Override
    public List<TwoLevelVo> queryList(TwoLevelBo bo) {
        LambdaQueryWrapper<TwoLevel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TwoLevel> buildQueryWrapper(TwoLevelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TwoLevel> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMedicalRecordNo() != null, TwoLevel::getMedicalRecordNo, bo.getMedicalRecordNo());
        lqw.eq(StringUtils.isNotBlank(bo.getModerateRenalFunction()), TwoLevel::getModerateRenalFunction, bo.getModerateRenalFunction());
        lqw.eq(StringUtils.isNotBlank(bo.getAltValue()), TwoLevel::getAltValue, bo.getAltValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAstValue()), TwoLevel::getAstValue, bo.getAstValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAlpValue()), TwoLevel::getAlpValue, bo.getAlpValue());
        lqw.eq(StringUtils.isNotBlank(bo.getTbil()), TwoLevel::getTbil, bo.getTbil());
        lqw.eq(StringUtils.isNotBlank(bo.getCtpValue()), TwoLevel::getCtpValue, bo.getCtpValue());
        lqw.eq(StringUtils.isNotBlank(bo.getIsChild()), TwoLevel::getIsChild, bo.getIsChild());
        lqw.eq(StringUtils.isNotBlank(bo.getIsHistoryAllergy()), TwoLevel::getIsHistoryAllergy, bo.getIsHistoryAllergy());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSimultaneously()), TwoLevel::getIsSimultaneously, bo.getIsSimultaneously());
        lqw.eq(StringUtils.isNotBlank(bo.getIsVenousAntisepsis()), TwoLevel::getIsVenousAntisepsis, bo.getIsVenousAntisepsis());
        lqw.eq(StringUtils.isNotBlank(bo.getIsBadAntisepsis()), TwoLevel::getIsBadAntisepsis, bo.getIsBadAntisepsis());
        lqw.eq(StringUtils.isNotBlank(bo.getUnionThreeAntisepsis()), TwoLevel::getUnionThreeAntisepsis, bo.getUnionThreeAntisepsis());
        lqw.eq(StringUtils.isNotBlank(bo.getHighWarningPills()), TwoLevel::getHighWarningPills, bo.getHighWarningPills());
        lqw.eq(StringUtils.isNotBlank(bo.getExtremelyPoisonousDrugs()), TwoLevel::getExtremelyPoisonousDrugs, bo.getExtremelyPoisonousDrugs());
        lqw.eq(StringUtils.isNotBlank(bo.getIsVenousTransfusion()), TwoLevel::getIsVenousTransfusion, bo.getIsVenousTransfusion());
        lqw.eq(StringUtils.isNotBlank(bo.getCareLevelValue()), TwoLevel::getCareLevelValue, bo.getCareLevelValue());
        lqw.eq(StringUtils.isNotBlank(bo.getOneChronicDisease()), TwoLevel::getOneChronicDisease, bo.getOneChronicDisease());
        return lqw;
    }

    /**
     * 新增医学二级监护信息
     */
    @Override
    public Boolean insertByBo(TwoLevelBo bo) {
        TwoLevel add = BeanUtil.toBean(bo, TwoLevel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医学二级监护信息
     */
    @Override
    public Boolean updateByBo(TwoLevelBo bo) {
        TwoLevel update = BeanUtil.toBean(bo, TwoLevel.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TwoLevel entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除医学二级监护信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询医学二级监护信息详细信息
     *
     * @param medicalRecordNo 病历号
     * @return
     */
    @Override
    public TwoLevelVo queryByMedicalRecordNo(Integer medicalRecordNo) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<TwoLevel>().eq(TwoLevel::getMedicalRecordNo, medicalRecordNo));
    }

    /**
     * 新增或修改二级监护信息
     *
     * @param bo
     * @return
     */
    @Transactional
    @Override
    public Boolean insertOrUpdateByBo(TwoLevelBo bo) {
        try {
            // 更新二级监护信息
            TwoLevel twoLevel = BeanUtil.toBean(bo, TwoLevel.class);
            baseMapper.updateById(twoLevel);
            // 查询患者的基本信息
            PatientBaseInfo baseInfo = patientBaseInfoMapper.selectOne(new LambdaQueryWrapper<PatientBaseInfo>().eq(PatientBaseInfo::getMedicalRecordNo, twoLevel.getMedicalRecordNo()));
            if (ObjectUtil.isNotNull(twoLevel) && ObjectUtil.isNotNull(baseInfo)) {
                // 判断是否属于一级监护
                FirstLevel firstLevel = firstLevelMapper.selectOne(new LambdaQueryWrapper<FirstLevel>().eq(FirstLevel::getMedicalRecordNo, twoLevel.getMedicalRecordNo()));
                boolean isFirst = CareLevelUtil.isFirstCareLevel(baseInfo, firstLevel);
                if (isFirst) { // 属于一级监护
                    if (!DictConstants.GUARDIAN_LEVEL_THREE.equals(baseInfo.getGuardianLevel())) { // 当前监护不是一级监护，则更新为一级监护
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_THREE);
                    }
                } else {
                    // 判断是否属于二级监护
                    boolean isTwo = CareLevelUtil.isTwoCareLevel(baseInfo, twoLevel);
                    if (isTwo) { // 属于二级监护
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_TWO);
                    } else {
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_ONE);
                    }
                }
                // 更新患者药学监护分级
                patientBaseInfoMapper.updateById(baseInfo);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
